package com.pipodi.itasamobile.connections;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;

import android.util.Log;

public class POSTCallLoginItaSA extends HttpAbstract {

	private final String ADDRESS_ITASA = "http://www.italiansubs.net/index.php";
	private final String TAG_ITASA = "<h2><br /><center>";
	private CookieStore cookies;

	public POSTCallLoginItaSA(int timeout) {
		super(timeout);
	}

	public void connectItasa(String user, String pwd)
			throws UnsupportedEncodingException, ClientProtocolException,
			IOException {
		this.response = this.client.execute(setPostItasa(user, pwd));
		this.entity = this.response.getEntity();
		consumeEntity();
		getCookiesItasa();
	}

	public boolean testConnectItasa(String user, String pwd)
			throws ClientProtocolException, IOException {
		POSTCallLoginItaSA temp = new POSTCallLoginItaSA(10000);
		HttpResponse res = temp.client.execute(setPostItasa(user, pwd));
		String value = res.getHeaders("Location")[0].getValue();
		temp.closeClient();
		if (value
				.equals("http://www.italiansubs.net/index.php?option=com_user")) {
			return true;
		}
		return false;
	}

	private HttpPost setPostItasa(String user, String pwd)
			throws UnsupportedEncodingException {
		HttpPost post = new HttpPost("http://www.italiansubs.net/index.php");
		List<NameValuePair> lnvp = new ArrayList<NameValuePair>();
		lnvp.add(new BasicNameValuePair("username", user));
		lnvp.add(new BasicNameValuePair("passwd", pwd));
		lnvp.add(new BasicNameValuePair("remember", "yes"));
		lnvp.add(new BasicNameValuePair("Submit", "Login"));
		lnvp.add(new BasicNameValuePair("option", "com_user"));
		lnvp.add(new BasicNameValuePair("task", "login"));
		lnvp.add(new BasicNameValuePair("silent", "true"));
		post.setEntity(new UrlEncodedFormEntity(lnvp, "UTF-8"));
		Log.e("RETURN", "True");
		return post;
	}

	public HttpEntity requestGetEntity(String link)
			throws IndexOutOfBoundsException, IOException {
		long lenght = -1L;
		int temp = 0;
		while (lenght == -1L) {
			temp++;
			consumeEntity();
			this.client.setCookieStore(this.cookies);
			this.get = new HttpGet(link);
			this.response = this.client.execute(this.get);
			this.entity = this.response.getEntity();
			String url = readInputStreamURL(this.entity.getContent(),
					"<h2><br /><center>", 2);
			consumeEntity();
			if (url != null) {
				this.get = new HttpGet(url);
				this.client.setCookieStore(this.cookies);
				this.response = this.client.execute(this.get);
				this.entity = this.response.getEntity();
				lenght = this.entity.getContentLength();
				if (lenght != -1L) {
					getAttachement(this.response.getAllHeaders(),
							"http://www.italiansubs.net/index.php");
				}
				this.get = null;
				this.response = null;
				if (temp == 26) {
					break;
				}
			} else {
				this.entity = null;
				lenght = -2L;
			}
		}
		return this.entity;
	}

	private void getCookiesItasa() throws IOException {
		this.client.getParams().setParameter("http.protocol.cookie-policy",
				"compatibility");

		this.get = new HttpGet("http://www.italiansubs.net/index.php");
		this.response = this.client.execute(this.get);
		this.entity = this.response.getEntity();
		consumeEntity();
		this.cookies = this.client.getCookieStore();
	}

	private String readInputStreamURL(InputStream is, String tag, int start)
			throws StringIndexOutOfBoundsException, IOException {
		String search = null;
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		String line;
		while ((line = br.readLine()) != null) {
			int min = start;
			int max = start + tag.length();
			int len = line.length();
			if (len < max) {
				max = len;
			}
			if (len < min) {
				min = len;
			}
			if (line.substring(min, max).equalsIgnoreCase(tag)) {
				search = line;
				search = search.substring(search.indexOf('"') + 1);
				search = search.substring(0, search.indexOf('"'));
				break;
			}
		}
		br.close();
		return search;
	}

	@Override
	protected void getAttachement(Header[] head, String from)
			throws IndexOutOfBoundsException {
		for (int i = 0; i < head.length; i++) {
			if (head[i].getName().equalsIgnoreCase("Content-Disposition")) {
				break;
			}
			String attachement = head[i].getValue();
			this.namefile = attachement.substring(21);
		}
	}
}
